#region

using System;
using System.Linq;
using TimeDRODPOF.TDLib;
using VeeTileEngine2012;

#endregion

namespace TimeDRODPOF.TDComponents
{
    public class TDCPressurePlate : Component
    {
        private readonly TDCFloodFiller _floodFillerComponent;
        private readonly TDCIDCaller _idCallerComponent;

        public TDCPressurePlate(TDCFloodFiller mFloodFillerComponent, TDCIDCaller mIDCallerComponent)
        {
            _floodFillerComponent = mFloodFillerComponent;
            _idCallerComponent = mIDCallerComponent;
        }

        public bool Triggered { get; set; }
        public bool Tested { get; set; }
        public bool CallSent { get; set; }

        public void Trigger()
        {
            if (Triggered) return;
            foreach (var plate in _floodFillerComponent.GetAttachedEntities())
                plate.GetComponent<TDCPressurePlate>().Triggered = true;

            if (HasAnyNeighborSentCall()) return;

            _idCallerComponent.SendCalls();
            TDLHelper.PlaySound("SoundPressurePlate");

            foreach (var plate in _floodFillerComponent.GetAttachedEntities())
                plate.GetComponent<TDCPressurePlate>().CallSent = true;
        }

        public bool IsAnyNeighborOccupied()
        {
            return _floodFillerComponent.GetAttachedEntities().Any
                (x => x.Field.GetEntitiesByTag(x.X, x.Y, TDLTags.Solid).Any(y => !y.HasTag(TDLTags.DoesNotTriggerPlate)));
        }

        public bool HasAnyNeighborSentCall() { return _floodFillerComponent.GetAttachedEntities().Any(x => x.GetComponent<TDCPressurePlate>().CallSent); }
    }
}